﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using System.Collections;
using PMS.ReportViewer;
namespace PMS.ChucNang
{
    public partial class BienBanNhapKhoEntry : FormEntryBase
    {
        #region Constants
        private const string BINDING_PROPERTY = "EditValue";
        private string NEW_String = Messages.GetString(Constants.NEW);
        private const string DUPLICATE_PRODUCT_CODE = "DUPLICATE_PRODUCT_CODE";
        private const string CHITITENHAP_DONOT_EXISTED = "CHITITENHAP_DONOT_EXISTED";
        private const string PRODUCT_NOT_EXIST = "PRODUCT_NOT_EXIST";
        private const string INVALID_QUANTITY = "INVALID_QUANTITY";
        #endregion

        #region Private Members
        protected BienBanNhapHangBO m_Service;
        protected BaseEntityCollection<ChiTietBienBanNhapHang> m_DetailItemsList;
        protected ChiTietBienBanNhapHangBO m_ChiTietService;
        private bool m_isDuplicateProduct;
        protected SanPhamBO m_ProductService;
        #endregion

        #region Properties
        protected Entity.BienBanNhapHang CurrentBBNhapKhoEntry
        {
            get
            {
                return base.Entity as Entity.BienBanNhapHang;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public BienBanNhapHangBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new BienBanNhapHangBO();
                }
                return m_Service;
            }
        }

        public ChiTietBienBanNhapHangBO ChiTietService
        {
            get
            {
                if (m_ChiTietService == null)
                {
                    m_ChiTietService = new ChiTietBienBanNhapHangBO();
                }
                return m_ChiTietService;
            }
        }

        public SanPhamBO ProductService
        {
            get
            {
                if (m_ProductService == null)
                {
                    m_ProductService = new SanPhamBO();
                }
                return m_ProductService;
            }
        }
        #endregion

        #region Constructors
        public BienBanNhapKhoEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            m_DetailItemsList = new BaseEntityCollection<ChiTietBienBanNhapHang>();
            BindingToGrid();
        }

        private void InitStyle()
        {
            //grid
            grdDetail.CausesValidation = false;
            bteMaBBNK.Tag = "Ignore";
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;

            this.grvDetail.OptionsView.ShowFooter = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsView.ShowGroupPanel = false;
            this.grvDetail.OptionsCustomization.AllowColumnMoving = false;
            this.grvDetail.OptionsCustomization.AllowGroup = false;
            this.grvDetail.OptionsMenu.EnableColumnMenu = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsNavigation.EnterMoveNextColumn = true;
            this.grvDetail.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;
            this.grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            txtColSLNhap.Mask.MaskType = MaskType.Numeric;
            txtColSLNhap.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColSLNhap.Mask.UseMaskAsDisplayFormat = true;

            txtColThieu.Mask.MaskType = MaskType.Numeric;
            txtColThieu.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColThieu.Mask.UseMaskAsDisplayFormat = true;

            txtColThucTe.Mask.MaskType = MaskType.Numeric;
            txtColThucTe.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColThucTe.Mask.UseMaskAsDisplayFormat = true;

            txtColThua.Mask.MaskType = MaskType.Numeric;
            txtColThua.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColThua.Mask.UseMaskAsDisplayFormat = true;

            txtHong.Mask.MaskType = MaskType.Numeric;
            txtHong.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtHong.Mask.UseMaskAsDisplayFormat = true;


        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentBBNhapKhoEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteMaBBNK.DataBindings.Clear();
            this.txtSoHopDong.DataBindings.Clear();
            this.txtNoiNhan.DataBindings.Clear();
            this.dteNgayNhan.DataBindings.Clear();
            this.dteNgayKiem.DataBindings.Clear();
            this.txtKetQua.DataBindings.Clear();
            this.txtNguoiDuyet.DataBindings.Clear();
            this.txtKetToan.DataBindings.Clear();
            this.txtThuKho.DataBindings.Clear();

            this.bteMaBBNK.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.MaBBNH.ToString());
            this.txtSoHopDong.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.SoHopDong.ToString());
            this.txtNoiNhan.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.NoiNhan.ToString());
            this.dteNgayNhan.DataBindings.Add("DateTime", entity, BienBanNhapHangColumns.NgayGioNhan.ToString());
            this.dteNgayKiem.DataBindings.Add("DateTime", entity, BienBanNhapHangColumns.NgayGioKiem.ToString());
            this.txtKetQua.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.KetQua.ToString());
            this.txtNguoiDuyet.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.NguoiDuyet.ToString());
            this.txtKetToan.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.KeToan.ToString());
            this.txtThuKho.DataBindings.Add(BINDING_PROPERTY, entity, BienBanNhapHangColumns.ThuKho.ToString());

            BienBanNhapHang bbnh = entity as BienBanNhapHang;
            m_DetailItemsList.Clear();
            m_DetailItemsList.AddRange(ChiTietService.GetAllChiTietBienBanNhapHangByMaBBNH(bbnh.MaBBNH));

            if (bbnh.MaBBNH == NEW_String)
            {
                CanPrint = false;
            }
            else
            {
                CanPrint = true;
            }
        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.txtSoHopDong.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            //add new validation rules here

        }

        public override void New()
        {
            this.CurrentBBNhapKhoEntry = new Entity.BienBanNhapHang()
            {
                NgayGioNhan = Constants.BUSINESS_DATE,
                NgayGioKiem = Constants.BUSINESS_DATE,
                MaBBNH = NEW_String
            };
            base.New();
        }

        protected override bool Save()
        {
            try
            {
                ChiTietBienBanNhapHangs list = new ChiTietBienBanNhapHangs();
                list.AddRange(m_DetailItemsList);
                if (IsNew)
                {
                    CurrentBBNhapKhoEntry = Service.CreateBienBanNhapHang(CurrentBBNhapKhoEntry, list);
                }
                else
                {
                    Service.UpdateBienBanNhapHang(CurrentBBNhapKhoEntry, list);
                }
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }

        }

        protected override bool Delete()
        {
            try
            {
                Service.DeleteBienBanNhapHang(CurrentBBNhapKhoEntry);
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override void Print()
        {
            try
            {
                BienBanNhapKhoViewer rpViewer = new BienBanNhapKhoViewer(CurrentBBNhapKhoEntry.MaBBNH);
                rpViewer.StartPosition = FormStartPosition.CenterParent;
                rpViewer.WindowState = FormWindowState.Maximized;
                rpViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void BindingToGrid()
        {
            colSoPN.FieldName = ChiTietPhieuNhapColumns.SoPN.ToString();
            colMaThuoc.FieldName = LuuKhoColumns.MaThuoc.ToString();
            ColSoLo.FieldName = LuuKhoColumns.SoLo.ToString();
            colUnit.FieldName = DonViTinhColumns.TenDonVi.ToString();
            colSLNhap.FieldName = ChiTietPhieuNhapColumns.SoLuong.ToString();
            colThucTe.FieldName = ChiTietBienBanNhapHangColumns.ThucTe.ToString();
            //colThucTe.FieldName = ChiTietPhieuNhapColumns.SoLuong.ToString();  //Assign ThucTe = SLNhap default
            colThua.FieldName = ChiTietBienBanNhapHangColumns.Thua.ToString();
            colThieu.FieldName = ChiTietBienBanNhapHangColumns.Thieu.ToString();
            colHong.FieldName = ChiTietBienBanNhapHangColumns.Hong.ToString();
            colTinhTrang.FieldName = ChiTietBienBanNhapHangColumns.TinhTrang.ToString();
            colGhiChu.FieldName = ChiTietBienBanNhapHangColumns.GhiChu.ToString();
            grdDetail.DataSource = m_DetailItemsList;
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentBBNhapKhoEntry.MaBBNH = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentBBNhapKhoEntry.MaBBNH = code;
                        Entity = CurrentBBNhapKhoEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentBBNhapKhoEntry = new BienBanNhapHang();
                            CurrentBBNhapKhoEntry.MaBBNH = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentBBNhapKhoEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentBBNhapKhoEntry.MaBBNH = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentBBNhapKhoEntry = new BienBanNhapHang();
                            CurrentBBNhapKhoEntry.MaBBNH = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentBBNhapKhoEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }

        private void LoadingProductToGrid(SanPham loadingProduct)
        {
            ChiTietBienBanNhapHang getRow = grvDetail.GetFocusedRow() as ChiTietBienBanNhapHang;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaThuoc = loadingProduct.MaThuoc;
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadingChiTietNhapToGrid(ChiTietPhieuNhap loadingProduct)
        {
            ChiTietBienBanNhapHang getRow = grvDetail.GetFocusedRow() as ChiTietBienBanNhapHang;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaThuoc = loadingProduct.MaThuoc;
            getRow.SoLo = loadingProduct.SoLo;
            getRow.MaCTPN = loadingProduct.MaCTPN;
            getRow.SoPN = loadingProduct.SoPN;
            getRow.TenDonVi = loadingProduct.TenDonVi;
            grvDetail.SetFocusedRowCellValue(colThua, 0);
            grvDetail.SetFocusedRowCellValue(colThieu, 0);
            grvDetail.SetFocusedRowCellValue(colHong, 0);
            getRow.SoLuong = loadingProduct.SoLuong;
            grvDetail.SetFocusedRowCellValue(colThucTe, getRow.SoLuong);//assign ThucTe equal SoLuong by default 
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }
        #endregion

        private void bteMaBBNK_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var form = new BienBanNhapKhoLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.BienBanNhapHangSelected != null)
                    {
                        LoadObjectOnForm(bteMaBBNK.Text.Trim(), form.BienBanNhapHangSelected.MaBBNH, form.BienBanNhapHangSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaBBNK_Enter(object sender, EventArgs e)
        {
            if (bteMaBBNK.Text.Equals(NEW_String))
            {
                bteMaBBNK.Text = string.Empty;
            }
        }

        private void bteMaBBNK_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(bteMaBBNK.Text) && !IsNew)
                {
                    New();
                }
                else
                {
                    if (CurrentBBNhapKhoEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentBBNhapKhoEntry.MaBBNH);
                    string code = DataConvertUltils.ToString(bteMaBBNK.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        BienBanNhapHang temPhieuXuat = Service.GetBienBanNhapHangByID(code);
                        LoadObjectOnForm(previousCode, code, temPhieuXuat);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void dteNgayNhan_EditValueChanged(object sender, EventArgs e)
        {
            if (dteNgayNhan.IsModified)
            {
                CurrentBBNhapKhoEntry.NgayGioNhan = dteNgayNhan.DateTime;
            }
        }

        private void dteNgayKiem_EditValueChanged(object sender, EventArgs e)
        {
            if (dteNgayKiem.IsModified)
            {
                CurrentBBNhapKhoEntry.NgayGioKiem = dteNgayKiem.DateTime;
            }
        }

        private void bteColMaThuoc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ProductLookup form = new ProductLookup(true);
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.ProductSelected != null)
                {
                    LoadingProductToGrid(form.ProductSelected);
                }
            }
        }

        private void bteColSoLo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ChiTietBienBanNhapHang row = grvDetail.GetFocusedRow() as ChiTietBienBanNhapHang;
            if (row != null)
            {
                ChiTietNhapLookup form = new ChiTietNhapLookup(0, row.MaThuoc);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.ChiTietPhieuNhapSelected != null)
                    {
                        LoadingChiTietNhapToGrid(form.ChiTietPhieuNhapSelected);
                    }
                }
            }
        }

        private void grvDetail_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if ((e.Info.IsRowIndicator) && (e.RowHandle >= 0))
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void grvDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.grvDetail.IsRowSelected(this.grvDetail.FocusedRowHandle) == true)
                {
                    ChiTietBienBanNhapHang row = (ChiTietBienBanNhapHang)this.grvDetail.GetRow(grvDetail.FocusedRowHandle);
                    int index = this.m_DetailItemsList.IndexOf(row);
                    if (index != -1)
                    {
                        bool isNewRow = (row.RowStatus == (byte)RowStatus.New);

                        this.m_DetailItemsList.RemoveAt(index);
                        if (isNewRow == true)
                        {
                            this.m_DetailItemsList.RemoveRows.Remove(row);
                        }
                        base.IsDataChanged = true;


                        decimal total = 0;
                        foreach (ChiTietBienBanNhapHang item in m_DetailItemsList)
                        {
                            total = total + item.Total;
                        }

                    }
                }
            }
            else if (e.KeyCode == Keys.F3)
            {
                if (this.grvDetail.FocusedColumn == this.colMaThuoc)
                {
                    bteColMaThuoc_ButtonClick(sender, new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(this.bteColMaThuoc.Buttons[0]));
                }
                else if (this.grvDetail.FocusedColumn == ColSoLo)
                {
                    bteColSoLo_ButtonClick(sender, new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(this.bteColSoLo.Buttons[0]));
                }
            }
        }

        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        private void grvDetail_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void grvDetail_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (grvDetail.FocusedColumn == colSoPN)
            {
                e.Cancel = true;
                return;
            }
            ChiTietBienBanNhapHang row = grvDetail.GetFocusedRow() as ChiTietBienBanNhapHang;
            if (row == null)
            {
                if (grvDetail.FocusedColumn != colMaThuoc)
                {
                    e.Cancel = true;
                }

            }
            else
            {
                if (string.IsNullOrEmpty(row.MaThuoc))
                {
                    if (grvDetail.FocusedColumn != colMaThuoc)
                    {
                        e.Cancel = true;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(row.SoLo))
                    {
                        if (grvDetail.FocusedColumn == colMaThuoc || grvDetail.FocusedColumn == ColSoLo)
                        {
                            e.Cancel = false;
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                    }
                    else
                    {
                        e.Cancel = false;
                    }
                }
            }
        }

        private void grvDetail_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            ChiTietBienBanNhapHang currentRow = grvDetail.GetFocusedRow() as ChiTietBienBanNhapHang;
            DevExpress.XtraGrid.Columns.GridColumn errorColumn = null;
            if (currentRow != null)
            {
                if (currentRow.Thieu < 0)
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colThieu, Messages.GetString(INVALID_QUANTITY));
                    errorColumn = colThieu;
                }

                if (currentRow.Thua < 0)
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colThua, Messages.GetString(INVALID_QUANTITY));
                    errorColumn = colThua;
                }

                if (currentRow.Hong < 0)
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colHong, Messages.GetString(INVALID_QUANTITY));
                    errorColumn = colHong;
                }

                if (string.IsNullOrEmpty(currentRow.MaThuoc))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colMaThuoc, Messages.GetString(Constants.REQUIRE_FIELD));
                    errorColumn = colMaThuoc;
                }
                else
                {
                    SanPham tempProduct = ProductService.GetSanPhamByID(currentRow.MaThuoc);
                    if (tempProduct == null)
                    {
                        e.Valid = false;
                        grvDetail.SetColumnError(colMaThuoc, Messages.GetString(PRODUCT_NOT_EXIST));
                        errorColumn = colMaThuoc;
                    }
                }

                if (string.IsNullOrEmpty(currentRow.SoLo))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(ColSoLo, Messages.GetString(Constants.REQUIRE_FIELD));
                    errorColumn = ColSoLo;
                }
                else
                {
                    if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    {
                        int duplicate = -1;
                        int index = m_DetailItemsList.IndexOf(currentRow);
                        if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                        {
                            for (int i = 0; i < m_DetailItemsList.Count; i++)
                            {
                                ChiTietBienBanNhapHang temprow = m_DetailItemsList[i];
                                if (temprow.MaCTPN.Equals(currentRow.MaCTPN, StringComparison.CurrentCultureIgnoreCase) && index != i && temprow.SoLo.Equals(currentRow.SoLo, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    duplicate = i;
                                }
                            }
                        }

                        if (duplicate >= 0)
                        {
                            grvDetail.SetColumnError(ColSoLo, string.Format(Messages.GetString(DUPLICATE_PRODUCT_CODE),duplicate));
                            e.Valid = false;
                            errorColumn = ColSoLo;
                            m_isDuplicateProduct = true;
                        }
                        else
                        {
                            m_isDuplicateProduct = false;
                        }
                    }
                }
            }
            if (errorColumn != null)
            {
                grvDetail.FocusedColumn = errorColumn;
            }
        }

        private void grvDetail_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            ChiTietBienBanNhapHang row = grvDetail.GetFocusedRow() as ChiTietBienBanNhapHang;
            if (grvDetail.FocusedColumn == colThieu || grvDetail.FocusedColumn == colHong || grvDetail.FocusedColumn == colThua)
            {
                int qty = DataConvertUltils.ToInt(e.Value);
                if (qty < 0)
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(INVALID_QUANTITY);
                }
            }
            else if (grvDetail.FocusedColumn == colMaThuoc)
            {
                string productCode = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(productCode))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    SanPham temProduct = ProductService.GetSanPhamByID(productCode);
                    if (temProduct == null)
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(PRODUCT_NOT_EXIST);
                    }
                    else
                    {
                        e.Value = temProduct.MaThuoc;
                        LoadingProductToGrid(temProduct);
                    }
                }
            }
            else if (grvDetail.FocusedColumn == ColSoLo)
            {
                string solo = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(solo))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    ChiTietPhieuNhap nhap = (new ChiTietPhieuNhapBO()).GetChiTietPhieuNhapByMaThuocAndSoLo(row.MaThuoc, solo);
                    if (nhap != null)
                    {
                        LoadingChiTietNhapToGrid(nhap);
                    }
                    else
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(CHITITENHAP_DONOT_EXISTED);
                    }
                    if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    {
                        int duplicate = -1;
                        int index = m_DetailItemsList.IndexOf(row);
                        if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                        {
                            for (int i = 0; i < m_DetailItemsList.Count; i++)
                            {
                                ChiTietPhieuNhap temprow = m_DetailItemsList[i];
                                if (temprow.MaCTPN.Equals(row.MaCTPN, StringComparison.CurrentCultureIgnoreCase) && index != i && temprow.SoLo.Equals(row.SoLo, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    duplicate = i;
                                }
                            }
                        }

                        if (duplicate >= 0)
                        {
                            e.ErrorText = string.Format(Messages.GetString(DUPLICATE_PRODUCT_CODE),duplicate);
                            e.Valid = false;
                            m_isDuplicateProduct = true;
                        }
                        else
                        {
                            m_isDuplicateProduct = false;
                        }
                    }
                }
            }
        }
    }
}
